<template>
  <div class="upload_wrap">
    <div class="title_text" v-if="!previewVisible">{{ title }}</div>
    <!-- 文件上传 -->
    <div class="upload-container" v-if="!previewVisible" @click="uploadClick">
      <div class="upload_title">Select a portrait photo</div>
      <van-uploader v-model="fileList" :max-count="1" :before-read="beforeRead" :after-read="handleUpload"
        :before-delete="handleDelete" accept="image/*" :max-size="5 * 1024 * 1024" @oversize="handleOversize"
        v-if="authStore.isAuthenticated">
        <div class="uploadBtn">
          <img src="@/assets/images/ic_select_photo@2x.png" class="upload_img" />
        </div>
      </van-uploader>
      <!-- 未登录时 -->
      <div class="uploadBtn" v-else>
        <img src="@/assets/images/ic_select_photo@2x.png" class="upload_img" />
      </div>
      <ul class="upload_tips">
        <li>1.Upload clear photos of people for better results</li>
        <li>2.Your uploads are solely for AI processing with no leakage risk. Use confidently.</li>
      </ul>
    </div>
    <!-- 上传成功，图片回显 -->
    <div class="upload_sucess_show" v-else>
      <img :src="previewImageUrl" class="upload_fixed" />
      <div class="close_wrap" @click="handleDelete">
        <van-icon name="cross" />
      </div>
    </div>
    <!-- 自定义loading弹框 -->
    <van-dialog v-model:show="showSubmitDialog" title="" :showConfirmButton="false" className="oss_upload_dialog">
      <img src="@/assets/images/airplane@2x.png" />
      <!-- <div class="tips_word">Submitting...</div> -->
      <div class="wave-text">
        <span>S</span>
        <span>u</span>
        <span>b</span>
        <span>m</span>
        <span>i</span>
        <span>t</span>
        <span>t</span>
        <span>i</span>
        <span>n</span>
        <span>g</span>
        <span>.</span>
        <span>.</span>
        <span>.</span>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { Toast, showFailToast, showToast } from "vant";
import { createOSSClient } from "@/utils/oss";
import api from "@/api";
import { useRoute } from "vue-router";
import { trackEvent } from "@/utils/firebase";
import Compressor from "compressorjs";
import { useAuthStore } from "@/stores/authStore";

defineProps({
  title: {
    type: String,
    required: true,
  },
});

const route = useRoute();
const authStore = useAuthStore();

const emit = defineEmits(["uploadStatus"]);

const fileList = ref([]); // 存储上传文件信息
const previewVisible = ref(false); // 预览弹窗显示状态
const previewImageUrl = ref(""); // 预览图片URL
const showSubmitDialog = ref(false);

const ossClient = ref(null);
// 获取oss参数
const getOSSParms = async () => {
  try {
    const response = await api.ossCredentials();
    const ossConfig = response.data;
    ossClient.value = createOSSClient(ossConfig);
  } catch (err) {
    console.log(err);
  }
};

// 生成本地预览 URL
const generatePreviewUrl = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsDataURL(file); // 读取为Base64
    reader.onload = () => {
      // 获取Base64字符串（包含data:前缀）
      const base64Data = reader.result;
      resolve(base64Data);
    };
  });
};

// 点击上传
const uploadClick = (event) => {
  if (!authStore.isAuthenticated) {
    event.stopPropagation(); // 阻止事件冒泡
    authStore.showLoginDialog(); // 触发登录弹窗
    authStore.isLogin = true;
    return false;
  }
  trackEvent(route.path === "/" ? "首页RemoveOff_点击【上传图片】" : "AI Pose_点击【上传图片】", {
    id: route.path === "/" ? "100021" : "100031",
  }); //埋点
};

// 上传前处理
const beforeRead = (file) => {
  return true; // 继续上传流程
};

const handleUpload = async (file) => {
  try {
    // 初始化状态
    file.status = "uploading";
    showSubmitDialog.value = true;
    const fileObj = Array.isArray(file) ? file[0] : file;

    // 文件有效性校验
    if (!fileObj?.file || !(fileObj.file instanceof File)) {
      throw new Error("Invalid file object");
    }
    // 图片压缩逻辑
    const compressedFile = await new Promise((resolve, reject) => {
      new Compressor(fileObj.file, {
        quality: 0.6,
        maxWidth: 1280,
        maxHeight: 768,
        convertSize: 500000, // 超过500KB自动转WebP
        checkOrientation: true,
        success(result) {
          // 保留原始文件名和类型
          const compressed = new File([result], fileObj.file.name, {
            type: result.type || "image/jpeg",
          });
          resolve(compressed);
        },
        error(err) {
          console.error("压缩错误详情:", err);
          reject(new Error(`Compression failed: ${err.message}`));
        },
      });
    });

    // OSS上传配置
    const uploadConfig = {
      headers: {
        "Content-Type": compressedFile.type || "image/jpeg",
      },
      progress: (p) => {
        console.log(`上传进度: ${(p * 100).toFixed(2)}%`);
        // 可在此处添加UI进度条更新逻辑
      },
    };

    // 执行上传
    const result = await ossClient.value.put(
      `images/${encodeURIComponent("comfyui/input/" + fileObj.file.name)}`,
      compressedFile,
      uploadConfig
    );

    // 等待Promise解析为Base64字符串
    const base64Data = await generatePreviewUrl(compressedFile);
    previewImageUrl.value = base64Data; // 直接赋值Base64字符串
    previewVisible.value = true;
    file.status = "done";
    showSubmitDialog.value = false;

    // 业务逻辑处理
    showToast("Upload successful");
    emit("uploadStatus", { status: true, url: result.url });

    // 根据当前页面，缓存oss返回的图片
    if (route.path === "/") {
      sessionStorage.setItem("removeossUrl", result.url);
      sessionStorage.setItem("removeCoverUrl", previewImageUrl.value);
      sessionStorage.setItem("removeAiposeCover", previewImageUrl.value);
    } else {
      sessionStorage.setItem("poseossUrl", result.url);
      sessionStorage.setItem("poseossCoverUrl", previewImageUrl.value);
      sessionStorage.setItem("aiposeCover", previewImageUrl.value);
    }

    trackEvent(
      route.path === "/" ? "首页RemoveOff_上传图片至网页成功" : "AI Pose__上传图片至网页成功",
      { id: route.path === "/" ? "100022" : "100032" }
    ); //埋点
  } catch (err) {
    console.error("上传错误堆栈:", err);
    showSubmitDialog.value = false;
    file.status = "failed";
    showFailToast(`Upload failed: ${err.message || "unknown error"}`);
    emit("uploadStatus", { status: false, url: "" });
  }
};

onMounted(() => {
  getOSSParms();
  // 判断当前页面,获取缓存图片回显
  const removeossUrl = sessionStorage.getItem("removeossUrl");
  const getRemoveUrl = sessionStorage.getItem("removeCoverUrl");
  const poseossUrl = sessionStorage.getItem("poseossUrl");
  const getPoseUrl = sessionStorage.getItem("poseossCoverUrl");
  if (route.path === "/" && getRemoveUrl) {
    previewVisible.value = true;
    previewImageUrl.value = getRemoveUrl;
    emit("uploadStatus", { status: true, url: removeossUrl });
  } else if (route.path === "/createStep" && getPoseUrl) {
    previewVisible.value = true;
    previewImageUrl.value = getPoseUrl;
    emit("uploadStatus", { status: true, url: poseossUrl });
  } else if (route.path === "/createStep" && route.query.refer === "remove") {
    // 这个情况是从“/removeCreating”页面点击“ai pose”跳到‘/createStep“回显
    previewVisible.value = true;
    previewImageUrl.value = sessionStorage.getItem("removeAiposeCover");
  }
});

// 组件销毁前清除指定数据
onBeforeUnmount(() => {
  sessionStorage.removeItem("removeCoverUrl");
  sessionStorage.removeItem("poseossCoverUrl");
});

// 处理文件删除
const handleDelete = () => {
  // 删除前确认
  // return window.confirm("确定删除图片吗？");
  // 更新前端列表
  // fileList.value = fileList.value.filter(item => item.id !== file.id);
  fileList.value = [];
  previewVisible.value = false;
  emit("uploadStatus", { status: false, url: "" });
  if (route.path === "/") {
    sessionStorage.removeItem("removeossUrl");
    sessionStorage.removeItem("removeCoverUrl");
  } else {
    sessionStorage.removeItem("poseossUrl");
    sessionStorage.removeItem("poseossCoverUrl");
  }

  trackEvent(
    route.path === "/" ? "首页RemoveOff_已上传图片_删除图片" : "AI Pose__已上传图片_删除图片",
    { id: route.path === "/" ? "100023" : "100033" }
  ); //埋点
};

// 处理文件过大
const handleOversize = () => {
  Toast("The image size cannot exceed 5MB");
};
</script>

<style scoped lang="less">
.upload_wrap :deep(.oss_upload_dialog) {
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  padding: 32px 0;

  .van-dialog__content {
    display: flex;
    justify-content: center;
    flex-direction: column;
  }

  img {
    width: 96px;
  }

  .wave-text {
    font-size: 18px;
    color: rgba(0, 0, 0, 0.95);
    line-height: 22px;
    text-align: center;
    margin-top: 8px;
    display: inline-block;
    white-space: nowrap;
    filter: drop-shadow(0 2px 4px rgba(64, 158, 255, 0.3));
  }

  .wave-text span {
    display: inline-block;
    animation: wave 1.2s ease-in-out infinite;
    transform-origin: 50% 100%;
  }

  /* 波浪核心动画 */
  @keyframes wave {

    0%,
    100% {
      transform: translateY(0) scaleY(1);
    }

    25% {
      transform: translateY(-12px) scaleY(0.9);
    }

    50% {
      transform: translateY(-8px) scaleY(0.95);
    }

    75% {
      transform: translateY(-10px) scaleY(0.92);
    }
  }

  /* 字母错位动画 */
  .wave-text span:nth-child(odd) {
    animation-delay: calc(var(--i) * 0.04s);
  }

  .wave-text span:nth-child(even) {
    animation-delay: calc(var(--i) * 0.02s);
  }

  /* 生成序列类 */
  .wave-text span:nth-child(1) {
    --i: 0;
  }

  .wave-text span:nth-child(2) {
    --i: 1;
  }

  .wave-text span:nth-child(3) {
    --i: 2;
  }

  .wave-text span:nth-child(4) {
    --i: 3;
  }

  .wave-text span:nth-child(5) {
    --i: 4;
  }

  .wave-text span:nth-child(6) {
    --i: 5;
  }

  .wave-text span:nth-child(7) {
    --i: 6;
  }

  .wave-text span:nth-child(8) {
    --i: 7;
  }

  .wave-text span:nth-child(9) {
    --i: 8;
  }

  .wave-text span:nth-child(10) {
    --i: 9;
  }

  .wave-text span:nth-child(11) {
    --i: 10;
  }

  .wave-text span:nth-child(12) {
    --i: 11;
  }

  .wave-text span:nth-child(13) {
    --i: 12;
  }
}

.upload_wrap {
  width: 100%;
  background: #efeeff;

  .title_text {
    width: 100%;
    text-align: center;
    background: #6251ff;
    font-size: 16px;
    line-height: 19px;
    color: #ffffff;
    padding: 8px 12px;
  }

  .upload-container {
    min-height: 174px;
    background: #efeeff;

    .upload_title {
      font-size: 14px;
      text-align: center;
      color: #3f39f2;
      padding: 8px 0;
    }

    .van-uploader__input-wrapper {
      width: 72px;
      height: 72px;
    }

    .uploadBtn {
      width: 72px;
      height: 72px;
      border: 2px dashed #ccc;
      margin: 0 auto;
      cursor: pointer;
      border-radius: 6px;
      position: relative;
      overflow: hidden;

      /* 防止动画溢出 */
      .upload_img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
        /* 基础过渡效果 */
        animation: zoom-in-out 1.5s infinite linear;
        /* 核心动画 */
      }
    }

    :deep(.van-uploader) {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    /* 定义缩放动画 */
    @keyframes zoom-in-out {

      0%,
      100% {
        transform: scale(1);
      }

      50% {
        transform: scale(1.1);
      }
    }

    /* 悬停增强效果（可选） */
    .uploadBtn:hover .upload_img {
      animation-play-state: paused;
      /* 悬停时暂停动画 */
      transform: scale(1.1);
    }

    .upload_tips {
      box-sizing: border-box;
      padding: 0 8px;

      li {
        font-size: 12px;
        color: rgba(0, 0, 0, 0.45);
        text-align: left;
        text-indent: em;
      }
    }
  }

  .upload_sucess_show {
    width: 100%;
    height: 200px;
    margin-top: 8px;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1.06667vw solid;
    border-image: linear-gradient(90deg, rgba(255, 213, 47, 1), rgba(248, 116, 255, 1), rgba(81, 110, 255, 1)) 4 4;

    .upload_fixed {
      max-width: 100%;
      max-height: 100%;
      width: auto;
      height: auto;
      object-fit: contain;
    }

    .close_wrap {
      width: 24px;
      height: 24px;
      background: rgba(0, 0, 0, 0.45);
      position: absolute;
      right: 0;
      top: 0;
      text-align: center;
      line-height: 24px;

      .van-icon {
        font-size: 18px;
        color: #fff;
        font-weight: 700;
      }
    }
  }
}
</style>
